<template>
    <el-dialog v-model="visible" :title="dialogTitle" width="600px" :modal="true" :show-close="true"
        @close="handleClose" class="gift-edit-dialog">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" class="gift-form">
            <el-form-item label="礼物名称" prop="name" required>
                <el-input v-model="formData.name" placeholder="请输入礼物名称" clearable />
            </el-form-item>

            <!-- <el-form-item label="分类" prop="cid" required>
                <el-select v-model="formData.cid" placeholder="请选择分类" style="width: 100%" clearable>
                    <el-option label="分类1" value="1" />
                    <el-option label="分类2" value="2" />
                    <el-option label="分类3" value="3" />
                </el-select>
            </el-form-item> -->

            <el-form-item label="普通价格" prop="price" required>
                <el-input v-model="formData.price" placeholder="0" type="number" clearable />
            </el-form-item>

            <el-form-item label="豪华价格" prop="vip_price" required>
                <el-input v-model="formData.vip_price" placeholder="0" type="number" clearable />
            </el-form-item>

            <el-form-item label="尊享价格" prop="svip_price" required>
                <el-input v-model="formData.svip_price" placeholder="0" type="number" clearable />
            </el-form-item>

            <el-form-item label="图片">
                <el-upload
                    class="avatar-uploader"
                    :action="upLoadUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="formData.cover" :src="formData.cover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="描述">
                <el-input v-model="formData.desc" placeholder="请输入描述" type="textarea" :rows="3" clearable />
            </el-form-item>

            <el-form-item label="是否推荐" prop="is_recommend">
                <el-radio-group v-model="formData.is_recommend">
                    <el-radio value="0" size="large">不推荐</el-radio>
                    <el-radio value="1" size="large">推荐</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="有效期">
                <el-input-number v-model="formData.expire_time" clearable placeholder="请输入有效期" type="number" />
            </el-form-item>

            <el-form-item label="排序">
                <el-input-number v-model="formData.sort" clearable placeholder="请输入排序" type="number" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleConfirm" :loading="loading">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, UploadProps, FormRules } from 'element-plus'
import { apiFamilyGiftAddGift, apiFamilyGiftEditGift } from '@/api/rms'
import feedback from '@/utils/feedback'
interface FormData {
    family_id?: number | string,
    // cid?: number | string,
    name: string,
    price: number,
    vip_price: number,
    svip_price: number,
    expire_time: number,
    sort: number,
    cover: string,
    desc: string,
    is_recommend: string,
    type: number,
}

const props = defineProps<{
    modelValue: boolean
    editData?: any,
    family_id?: number | string | any,
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'confirm': [data: any]
}>()


const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const loading = ref(false)
// 表单数据
const formData = reactive<FormData>({
    family_id: props.family_id,
    // cid: '',
    name: '',
    price: 0,
    vip_price: 0,
    svip_price: 0,
    expire_time: 0,
    sort: 0,
    cover: '',
    desc: '',
    is_recommend: '',
    type: 0,
})


// 表单验证
const formRules = reactive<any>({
    name: [{
        required: true,
        message: '请输入礼物名称',
        trigger: ['blur']
    }],
    // cid: [{
    //     required: true,
    //     message: '请选择分类',
    //     trigger: ['blur']
    // }],
    price: [{
        required: true,
        message: '请输入普通价格',
        trigger: ['blur']
    }
    // ,{
    //     validator: (rule: any, value: any, callback: any) => {
    //         if (value <= 0) {
    //             callback(new Error('请输入普通价格'))
    //         }
    //         callback()
    //     },
    //     trigger: ['blur']
    // }
    ],
    vip_price: [{
        required: true,
        message: '请输入豪华价格',
        trigger: ['blur']
    }
    // ,{
    //     validator: (rule: any, value: any, callback: any) => {
    //         if (value <= 0) {
    //             callback(new Error('请输入豪华价格'))
    //         }
    //         callback()
    //     },
    //     trigger: ['blur']
    // }
    ],
    svip_price: [{
        required: true,
        message: '请输入尊贵价格',
        trigger: ['blur']
    }
    // ,{
    //     validator: (rule: any, value: any, callback: any) => {
    //         if (value <= 0) {
    //             callback(new Error('请输入尊贵价格'))
    //         }
    //         callback()
    //     },
    //     trigger: ['blur']
    // }
    ],
    expire_time: [{
        required: true,
        message: '请输入有效期',
        trigger: ['blur']
    },{
        validator: (rule: any, value: any, callback: any) => {
            if (value <= 0) {
                callback(new Error('请输入有效期'))
            }
            callback()
        },
        trigger: ['blur']
    }],
    cover: [{
        required: true,
        message: '请上传图片',
        trigger: ['blur']
    }]
})

// 弹窗标题
const dialogTitle = computed(() => {
    return props.editData ? '编辑礼物' : '新增礼物'
})

// 监听编辑数据变化
// watch(() => props.editData, (newData) => {
//     if (newData) {
//         // 编辑模式，填充表单数据
//         Object.assign(formData, {
//             name: newData.name || '',
//             category: newData.category || '',
//             normalPrice: newData.normalPrice || 0,
//             luxuryPrice: newData.luxuryPrice || 0,
//             premiumPrice: newData.premiumPrice || 0,
//             image: newData.image || '',
//             description: newData.description || '',
//             type: newData.type || 'worship',
//             validDays: newData.validDays || 0,
//             sort: newData.sort || 0
//         })
//     } else {
//         // 新增模式，重置表单
//         // resetForm()
//     }
// }, { immediate: true })

// 监听弹窗显示状态
// watch(visible, (newVisible) => {
//     if (!newVisible) {
//         // 弹窗关闭时重置表单
//         setTimeout(() => {
//             // resetForm()
//         }, 300)
//     }
// })

const handleClose = () => {
    visible.value = false
    // resetForm()
}

const handleCancel = () => {
    handleClose()
}

const handleConfirm = async () => {
    try {
        await formRef.value?.validate()
        loading.value = true

        // 模拟API调用
        await apiFamilyGiftAddGift(formData)
        await feedback.msgSuccess('新增成功')
        // 触发确认事件，传递表单数据
        emit('confirm', { ...formData })

    } catch (error) {
        console.error('表单验证失败:', error)
    } finally {
        loading.value = false
    }
}

const resetForm = () => {
    formRef.value?.resetFields()
}

// 上传图片
const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image'
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    console.log(response, toRaw(uploadFile))
    if(response.code == 1){
        formData.cover = response.data.uri
    }else{
        feedback.msgError(response.msg)
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
    ElMessage.error('Avatar picture must be JPG、PNG、GIF format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.gift-edit-dialog {
    .el-dialog__header {
        padding: 20px 20px 10px;
        border-bottom: 1px solid #ebeef5;
    }

    .el-dialog__body {
        padding: 20px;
    }
}

.gift-form {
    .el-form-item {
        margin-bottom: 20px;
    }

    .el-form-item__label {
        font-weight: 500;
        color: #606266;
    }
}

.upload-container {
    .image-uploader {
        .upload-area {
            width: 100px;
            height: 100px;
            border: 2px dashed #d9d9d9;
            border-radius: 6px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: border-color 0.3s;

            &:hover {
                border-color: #409eff;
            }

            .upload-icon {
                font-size: 24px;
                color: #8c939d;
                margin-bottom: 8px;
            }

            .upload-text {
                color: #8c939d;
                font-size: 14px;
            }
        }
    }
}

.number-input-group {
    display: flex;
    align-items: center;
    width: 150px;

    .number-btn {
        width: 32px;
        height: 32px;
        padding: 0;
        border: 1px solid #dcdfe6;
        background: #fff;
        color: #606266;
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: center;

        &:first-child {
            border-radius: 4px 0 0 4px;
            border-right: none;
        }

        &:last-child {
            border-radius: 0 4px 4px 0;
            border-left: none;
        }

        &:hover:not(:disabled) {
            color: #409eff;
            border-color: #409eff;
        }

        &:disabled {
            color: #c0c4cc;
            cursor: not-allowed;
        }
    }

    .number-input {
        flex: 1;

        :deep(.el-input__wrapper) {
            border-radius: 0;
            text-align: center;
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

:deep(.el-radio-group) {
    .el-radio {
        margin-right: 20px;

        .el-radio__label {
            font-size: 14px;
        }
    }
}

.avatar-uploader{
    border: 1px dashed #cdd0d6;
    border-radius: 6px;
    overflow: hidden;
    width: 100px;
    height: 100px;
    box-sizing: border-box;
}
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: contain;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>